const fs = require('fs')
const path = require('path')
const url = require('url')

// 私有方法
let getFileMime = function (extname) {
  const data = fs.readFileSync('./data/mime.json')
  const mimeObj = JSON.parse(data.toString())
  return mimeObj[extname]
}

let app = {
  static: (req, res, staticPath) => {
    // 1、获取地址
    let pathname = url.parse(req.url).pathname
    pathname = pathname === '/' ? '/index.html' : pathname

    // 2、获取后缀名paht.extname()
    let extname = path.extname(pathname)

    // 3、通过fs模块读取文件
    if (pathname !== '/favicon.ico') {
      try {
        var data = fs.readFileSync('./' + staticPath + pathname)
        if (data) {
          let mime = getFileMime(extname)
          res.writeHead(200, { 'Content-Type': `${mime};charset="utf-8"` });
          res.end(data);
        }
      } catch (error) {
        console.log(error)
      }
    }
  },
  login: (req, res) => {
    fs.readFile('./views/form.ejs', {}, (error, data) => {
      res.writeHead(200, {'Content-Type' : 'text/html;charset="utf-8"'})
      res.end(data)
    })
  },
  news: (req, res) => {
    res.end('news')
  },
  doLogin: (req, res) => {
    let postData = ''
    req.on('data', (chunk) => {
      postData += chunk
    })
    req.on('end', () => {
      console.log(postData)
      res.end(postData)
    })
  },
  error: (req, res) => {
    res.end('error')
  }
}

module.exports = app